package com.haozi.provider;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.haozi.config.BaiduConfig;
import com.haozi.config.DataSourcelConfig;
import com.haozi.dto.BaiduResult;
import com.haozi.dto.PointResult;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author zyh
 * @version 1.0
 * @date 2022/4/27 11:06 上午
 */
@Service
public class BaiduProvider implements GetDataProvider {


    @Override
    public PointResult getData(DataSourcelConfig globalConfig) {

        BaiduConfig baiduConfig = (BaiduConfig) globalConfig;
        String url = baiduConfig.queryUrl();

        try {
            String response = HttpUtil.get(url);
            BaiduResult result = JSONObject.parseObject(response, BaiduResult.class);

            PointResult pointResult = new PointResult();
            pointResult.setSuccess(true);
            pointResult.setCurrentPoint(new BigDecimal(result.getResult().getCur().getPrice()));
            return pointResult;
        } catch (Exception ex) {
            PointResult pointResult = new PointResult();
            pointResult.setSuccess(false);
            return pointResult;
        }

    }

    @Override
    public boolean support(DataSourcelConfig globalConfig) {
        return globalConfig instanceof BaiduConfig;
    }


}
